#include "MultiUartManager.h"

MultiUartManager::MultiUartManager(size_t maxPorts) : maxPorts(maxPorts) {}

bool MultiUartManager::openPort(int portIndex, const std::string& portName, int baudRate) {
    if (portIndex < 0 || portIndex >= maxPorts) return false;

    std::lock_guard<std::mutex> lock(mutex);
    if (channels.find(portIndex) != channels.end()) return false;

    auto channel = std::make_unique<UartChannel>(portName, baudRate);
    if (channel->open()) {
        channels[portIndex] = std::move(channel);
        return true;
    }
    return false;
}

void MultiUartManager::closePort(int portIndex) {
    std::lock_guard<std::mutex> lock(mutex);
    if (channels.find(portIndex) != channels.end()) {
        channels[portIndex]->close();
        channels.erase(portIndex);
    }
}

bool MultiUartManager::sendData(int portIndex, const std::string& data) {
    std::lock_guard<std::mutex> lock(mutex);
    if (channels.find(portIndex) != channels.end()) {
        return channels[portIndex]->send(data);
    }
    return false;
}

void MultiUartManager::setReceiveCallback(int portIndex, ReceiveCallback callback) {
    std::lock_guard<std::mutex> lock(mutex);
    if (channels.find(portIndex) != channels.end()) {
        channels[portIndex]->setReceiveCallback(callback);
    }
}

void MultiUartManager::setStatusCallback(int portIndex, StatusCallback callback) {
    std::lock_guard<std::mutex> lock(mutex);
    if (channels.find(portIndex) != channels.end()) {
        channels[portIndex]->setStatusCallback(callback);
    }
}

bool MultiUartManager::isConnected(int portIndex) const {
    std::lock_guard<std::mutex> lock(mutex);
    if (channels.find(portIndex) != channels.end()) {
        return channels[portIndex]->isConnected();
    }
    return false;
}